package cn.maxwell.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * ZuulFilter类实现了IZuulFilter接口；该接口有四个核心方法
 */
@Component //将该类交给spring管理
public class LoginCheckFilter extends ZuulFilter {

    //filter类型 : "pre"前置
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 执行优先级 尽量不要使用负数定义
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 判断是否执行run方法里面的目标业务，返回true执行，返回false放行=>不执行run
     * @return
     */
    @Override
    public boolean shouldFilter() {
        //1.获取request对象 ，获取上下文路径， 获取请求中的url
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        String url = request.getRequestURI();
            if(url.endsWith("login") || url.endsWith("register")){
                return false;
            }
        return true;
    }

    /**
     * 执行目标业务的方法
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        //获取上下文对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        //获取请求对象
        HttpServletRequest request = currentContext.getRequest();
        //获取响应对象
        HttpServletResponse response = currentContext.getResponse();
        //获取请求头(里面包含token)
        String token = request.getHeader("token");
        //判断token是否为空
        if(!StringUtils.hasLength(token)){
            //3.1.返回登录检查失败的错误信息 :{ success:false, message:"登录检查失败，请重新登录"}
            Map<String,Object> resultMap = new HashMap<>();
            resultMap.put("success" , false);
            resultMap.put("message" , "登录检查失败，请重新登录");
            //中文编码
            response.setContentType("application/json;charset=utf-8");
            //把map转成json字符串，写到浏览器
            String resultJsonString = JSON.toJSONString(resultMap);

            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

            try {
                response.getWriter().print(resultJsonString);
            } catch (IOException e) {
                e.printStackTrace();
            }

            //3.2.阻止filter继续往后执行
            RequestContext.getCurrentContext().setSendZuulResponse(false);

        }
        return null;
    }
}
